<template>
  <div class="task-view-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>下载任务查看</span>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="模板文件名称">
            <el-input 
              v-model="searchForm.template_name" 
              placeholder="请输入模板文件名称"
              clearable
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="专业">
            <el-input 
              v-model="searchForm.major" 
              placeholder="请输入专业"
              clearable
              style="width: 150px;"
            />
          </el-form-item>
          <el-form-item label="年级">
            <el-input 
              v-model="searchForm.grade" 
              placeholder="请输入年级"
              clearable
              style="width: 120px;"
            />
          </el-form-item>
          <el-form-item label="课程名称">
            <el-input 
              v-model="searchForm.course_name" 
              placeholder="请输入课程名称"
              clearable
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="导出文件名">
            <el-input 
              v-model="searchForm.export_name" 
              placeholder="请输入导出文件名"
              clearable
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              搜索
            </el-button>
            <el-button @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 任务列表 -->
      <div class="table-section">
        <el-table 
          :data="taskList" 
          v-loading="loading"
          style="width: 100%"
          stripe
        >
          <el-table-column prop="id" label="任务序号" width="100" align="center" />
          <el-table-column prop="template_name" label="模板文件名称" min-width="200" show-overflow-tooltip />
          <el-table-column prop="major" label="专业" width="150" show-overflow-tooltip />
          <el-table-column prop="grade" label="年级" width="100" align="center" />
          <el-table-column prop="course_name" label="课程名称" min-width="200" show-overflow-tooltip />
          <el-table-column prop="export_name" label="导出文件名" min-width="200" show-overflow-tooltip />
          <el-table-column prop="init_time" label="创建时间" width="180" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.init_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="over_time" label="结束时间" width="180" align="center">
            <template #default="scope">
              {{ scope.row.over_time ? formatDateTime(scope.row.over_time) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="任务状态" width="120" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="scope">
              <div class="operation-buttons">
                <!-- 成功状态显示下载按钮 -->
                <el-button 
                  v-if="scope.row.status === 2"
                  type="primary" 
                  size="small" 
                  @click="handleDownload(scope.row)"
                  :loading="scope.row.downloading"
                >
                  下载
                </el-button>
                <!-- 失败状态且有错误信息时显示查看失败原因按钮 -->
                <el-button 
                  v-if="scope.row.status === 3 && scope.row.error_message"
                  type="danger" 
                  size="small" 
                  @click="handleViewError(scope.row)"
                >
                  查看失败原因
                </el-button>
                <!-- 其他状态显示 - -->
                <span v-if="!((scope.row.status === 2) || (scope.row.status === 3 && scope.row.error_message))">-</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 错误信息对话框 -->
    <el-dialog
      v-model="errorDialogVisible"
      title="任务失败原因"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="error-content">
        <div class="error-task-info">
          <p><strong>任务信息：</strong></p>
          <p>任务序号：{{ currentErrorTask.id }}</p>
          <p>模板文件：{{ currentErrorTask.template_name }}</p>
          <p>专业：{{ currentErrorTask.major }}</p>
          <p>年级：{{ currentErrorTask.grade }}</p>
          <p>课程名称：{{ currentErrorTask.course_name }}</p>
          <p>导出文件名：{{ currentErrorTask.export_name }}</p>
        </div>
        <div class="error-message">
          <p><strong>失败原因：</strong></p>
          <el-input
            v-model="currentErrorTask.error_message"
            type="textarea"
            :rows="6"
            readonly
            placeholder="暂无错误信息"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="errorDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { queryTasks } from '../api/taskApi.js'
import fileApi from '../api/fileApi.js'

// 响应式数据
const loading = ref(false)
const taskList = ref([])

// 搜索表单
const searchForm = reactive({
  template_name: '',
  major: '',
  grade: '',
  course_name: '',
  export_name: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 错误信息对话框相关
const errorDialogVisible = ref(false)
const currentErrorTask = reactive({
  id: '',
  template_name: '',
  major: '',
  grade: '',
  course_name: '',
  export_name: '',
  error_message: ''
})

// 获取任务列表
const getTaskList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize
    }

    // 添加搜索条件
    if (searchForm.template_name) {
      params.template_name = searchForm.template_name
    }
    if (searchForm.major) {
      params.major = searchForm.major
    }
    if (searchForm.grade) {
      params.grade = searchForm.grade
    }
    if (searchForm.course_name) {
      params.course_name = searchForm.course_name
    }
    if (searchForm.export_name) {
      params.export_name = searchForm.export_name
    }

    const response = await queryTasks(params)
    if (response.success === 0) {
      taskList.value = response.data.data || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取任务列表失败')
    }
    
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getTaskList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    template_name: '',
    major: '',
    grade: '',
    course_name: '',
    export_name: ''
  })
  pagination.currentPage = 1
  getTaskList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getTaskList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  getTaskList()
}

// 下载文件
const handleDownload = async (task) => {
  try {
    task.downloading = true
    
    // 调用下载接口，直接获取blob数据
    const blob = await fileApi.downloadTaskFile(task.id)
    
    // 获取文件名
    let filename = task.export_name || 'download'
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('文件下载成功')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请重试')
  } finally {
    task.downloading = false
  }
}

// 查看失败原因
const handleViewError = (task) => {
  currentErrorTask.id = task.id
  currentErrorTask.template_name = task.template_name
  currentErrorTask.major = task.major
  currentErrorTask.grade = task.grade
  currentErrorTask.course_name = task.course_name
  currentErrorTask.export_name = task.export_name
  currentErrorTask.error_message = task.error_message || '暂无错误信息'
  errorDialogVisible.value = true
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'info',    // 创建
    1: 'warning', // 运行中
    2: 'success', // 成功
    3: 'danger',  // 失败
    4: 'expired'  // 已过期
  }
  return statusMap[status] || 'danger'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '创建',
    1: '运行中',
    2: '成功',
    3: '失败',
    4: '已过期'
  }
  return statusMap[status] || '失败'
}

// 组件挂载时获取数据
onMounted(() => {
  getTaskList()
})
</script>

<style scoped>
.task-view-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.search-form {
  margin-bottom: 0;
}

.table-section {
  margin-top: 20px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.operation-buttons {
  display: flex;
  gap: 10px; /* 按钮之间的间距 */
}

:deep(.el-table .el-table__row) {
  cursor: pointer;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-tag) {
  font-weight: 500;
}

.error-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.error-task-info {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.error-task-info p {
  margin: 5px 0;
  line-height: 1.6;
}

.error-task-info p:first-child {
  margin-bottom: 10px;
  color: #409eff;
  font-weight: 600;
}

.error-message {
  flex: 1;
}

.error-message p {
  margin-bottom: 10px;
  font-weight: 600;
  color: #f56c6c;
}

.error-message p:last-child {
  margin-bottom: 0;
}

:deep(.el-textarea__inner) {
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
}
</style>
